package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.AuditService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.*;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.atguigu.tingshu.common.constant.SystemConstant.*;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Autowired
    private VodService vodService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * 保存声音
     *
     * @param trackInfoVo
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
        //1.根据所属专辑ID查询专辑信息 得到封面图片，用于后续更新
        Long albumId = trackInfoVo.getAlbumId();
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        if (albumInfo == null) {
            log.error("专辑:{}不存在", albumId);
            throw new GuiguException(404, "专辑不存在");
        }
        //2.新增声音记录
        //2.1 将声音VO转为PO
        TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);
        //2.2 给属性赋值
        //2.2.1 设置用户ID
        trackInfo.setUserId(userId);
        //2.2.2 设置声音序号 要求从1开始递增
        trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
        //2.2.3 调用点播平台获取音频详情信息：时长、大小、类型
        TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfo.getMediaFileId());
        if (trackMediaInfoVo != null) {
            trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
            trackInfo.setMediaType(trackMediaInfoVo.getType());
        }
        //2.2.4 来源：用户上传
        trackInfo.setSource(SystemConstant.TRACK_SOURCE_USER);
        //2.2.5 状态：待审核
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);
        //2.2.6 封面图片 如果未提交使用所属专辑封面
        String coverUrl = trackInfo.getCoverUrl();
        if (StringUtils.isBlank(coverUrl)) {
            trackInfo.setCoverUrl(albumInfo.getCoverUrl());
        }
        //2.3 新增声音记录
        trackInfoMapper.insert(trackInfo);
        Long trackId = trackInfo.getId();

        //3. 更新专辑信息：包含声音数量
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        albumInfoMapper.updateById(albumInfo);

        //4.新增声音统计记录
        this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PLAY, 0);
        this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COLLECT, 0);
        this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PRAISE, 0);
        this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COMMENT, 0);

        //5.内容审核-文本审核
        String content = trackInfo.getTrackTitle() + trackInfo.getTrackIntro();
        String suggestion = auditService.auditText(content);
        if ("pass".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_PASS);
            //6.对点播平台音频文件进行审核（异步审核）
            String reviewTaskId = auditService.startReviewTask(trackInfo.getMediaFileId());
            trackInfo.setStatus(TRACK_STATUS_REVIEWING);
            trackInfo.setReviewTaskId(reviewTaskId);
            trackInfoMapper.updateById(trackInfo);
        } else if ("review".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_REVIEWING);
        } else if ("block".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_NO_PASS);
        }
    }

    /**
     * 保存声音统计信息
     *
     * @param trackId  声音ID
     * @param statType 统计类型
     * @param statNum  统计数值
     */
    @Override
    public void saveTrackStat(Long trackId, String statType, int statNum) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statType);
        trackStat.setStatNum(statNum);
        trackStatMapper.insert(trackStat);
    }

    /**
     * 分页条件查询声音列表
     *
     * @param pageInfo       分页对象
     * @param trackInfoQuery 查询条件对象
     * @return
     */
    @Override
    public IPage<TrackListVo> findUserTrackPage(IPage<TrackListVo> pageInfo, TrackInfoQuery trackInfoQuery) {
        return trackInfoMapper.findUserTrackPage(pageInfo, trackInfoQuery);
    }

    /**
     * 更新声音信息
     *
     * @param id
     * @param trackInfoVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrackInfo(TrackInfoVo trackInfoVo, Long id) {
        //1.判断音频是否修改过
        //1.1 根据声音ID查询声音记录，得到更新前音频ID
        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        //1.2 对修改后的内容进行审核
        String content = trackInfoVo.getTrackTitle() + trackInfoVo.getTrackIntro();
        String suggestion = auditService.auditText(content);
        if ("pass".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_PASS);
        } else if ("review".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_REVIEWING);
        } else if ("block".equals(suggestion)) {
            trackInfo.setStatus(TRACK_STATUS_NO_PASS);
        }

        String oldMediaFileId = trackInfo.getMediaFileId();
        //1.2 跟参数中提交音频ID进行比较
        String newMediaFileId = trackInfoVo.getMediaFileId();
        if (!oldMediaFileId.equals(newMediaFileId)) {
            //2.如果修改过，获取新提交音频详情
            TrackMediaInfoVo trackMediaInfo = vodService.getTrackMediaInfo(newMediaFileId);
            if (trackMediaInfo != null) {
                trackInfo.setMediaUrl(trackInfoVo.getMediaUrl());
                trackInfo.setMediaFileId(newMediaFileId);
                trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfo.getDuration()));
                trackInfo.setMediaType(trackMediaInfo.getType());
                trackInfo.setMediaSize(trackMediaInfo.getSize());
            }
            //3.将原来旧文件从点播平台删除
            vodService.deleteTrackMedia(oldMediaFileId);
            //3.对修改后音频文件进行内容审核:发起审核任务
            String reviewTaskId = auditService.startReviewTask(trackInfo.getMediaFileId());
            trackInfo.setStatus(TRACK_STATUS_REVIEWING);
            trackInfo.setReviewTaskId(reviewTaskId);
        }
        //4.更新声音记录，审核状态：未通过
        trackInfoMapper.updateById(trackInfo);
    }


    /**
     * 删除声音信息
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTrackInfo(Long id) {
        //1.根据声音ID查询被删除声音信息，得到声音序号跟所属专辑ID
        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        Integer orderNum = trackInfo.getOrderNum();
        Long albumId = trackInfo.getAlbumId();

        //2.根据专辑ID查询专辑信息 更新包含声音数量
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        albumInfoMapper.updateById(albumInfo);

        //3.确保声音被删除后需要保持连续，更新序号
        LambdaUpdateWrapper<TrackInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("order_num = order_num - 1");
        updateWrapper.eq(TrackInfo::getAlbumId, albumId)
                .gt(TrackInfo::getOrderNum, orderNum);
        trackInfoMapper.update(null, updateWrapper);

        //4.删除声音信息
        trackInfoMapper.deleteById(id);

        //5.删除声音统计信息
        trackStatMapper.delete(
                new LambdaQueryWrapper<TrackStat>()
                        .eq(TrackStat::getTrackId, id)
        );

        //6.删除云点播文件
        vodService.deleteTrackMedia(trackInfo.getMediaFileId());
    }

    /**
     * 需求：用户未登录，可以给用户展示声音列表；用户已登录，可以给用户展示声音列表，并动态渲染付费标识
     * 分页查询专辑下声音列表（动态渲染付费标识）
     *
     * @param pageInfo MP分页对象
     * @param albumId  专辑ID
     * @param userId   用户ID
     * @return
     */
    @Override
    public IPage<AlbumTrackListVo> findAlbumTrackPage(IPage<AlbumTrackListVo> pageInfo, Long albumId, Long userId) {
        //1.分页获取声音列表（包含统计数值） isShowPaidMark默认为false
        pageInfo = trackInfoMapper.findAlbumTrackPage(pageInfo, albumId);

        //动态渲染付费标识
        //2.根据专辑ID查询专辑信息，得到专辑付费类型以及免费试听的集数
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        Assert.notNull(albumInfo, "专辑{}不存在", albumId);
        //2.1 付费类型：0101-免费、0102-vip免费、0103-付费
        String payType = albumInfo.getPayType();
        //2.2 免费试听集数
        Integer tracksForFree = albumInfo.getTracksForFree();
        //3.如果用户未登录 情况一：且专辑付费类型是：VIP免费或付费，将除试听以外其他声音付费标识设置true
        if (userId == null) {
            if (ALBUM_PAY_TYPE_VIPFREE.equals(payType) || ALBUM_PAY_TYPE_REQUIRE.equals(payType)) {
                pageInfo.getRecords()
                        .stream()
                        .filter(t -> t.getOrderNum() > tracksForFree)
                        .forEach(t -> t.setIsShowPaidMark(true));
            }
        } else {
            //4. 如果用户已登录 满足以下两种情况需要进一步获取当前页声音购买状态
            //4.1 远程调用用户服务获取用户身份，判断是否为会员（有效期内会员）
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
            Assert.notNull(userInfoVo, "用户{}不存在", userId);
            Boolean isVIP = false;
            if (userInfoVo.getIsVip().intValue() == 1 && userInfoVo.getVipExpireTime().after(new Date())) {
                isVIP = true;
            }

            //4.2 情况二：如果专辑 付费类型：VIP免费 且 当前用户是普通用户，满足进一步查询当前页声音购买状态
            Boolean isNeedCheckPayStatus = false;
            if (!isVIP && ALBUM_PAY_TYPE_VIPFREE.equals(payType)) {
                isNeedCheckPayStatus = true;
            }
            //4.3 情况三：如果专辑 付费类型：付费，无论什么用户，满足进一步查询当前页声音购买状态
            if (ALBUM_PAY_TYPE_REQUIRE.equals(payType)) {
                isNeedCheckPayStatus = true;
            }

            //4.4 如果满足情况二或情况三，远程调用用户服务，得到当前页除试听部分每个声音购买状态
            if (isNeedCheckPayStatus) {
                //4.4.1 获取当前页中除试听以外其他声音ID列表
                List<Long> needCheckPayStatusTrackIdList = pageInfo
                        .getRecords()
                        .stream()
                        .filter(t -> t.getOrderNum() > tracksForFree)
                        .map(AlbumTrackListVo::getTrackId)
                        .collect(Collectors.toList());

                //4.4.2 远程调用用户服务，获取当前页中声音购买状态Map<Long-专辑ID,Integer-购买状态>
                Map<Long, Integer> payStatusMap =
                        userFeignClient.userIsPaidTrack(userId, albumId, needCheckPayStatusTrackIdList).getData();

                //4.5 根据响应声音购买状态，动态修改付费标识。购买状态为0的声音付费标识isShowPaidMark全部设置：true
                pageInfo
                        .getRecords()
                        .stream()
                        .filter(t -> t.getOrderNum() > tracksForFree)
                        .forEach(t -> t.setIsShowPaidMark(payStatusMap.get(t.getTrackId()) == 0));
            }
        }
        return pageInfo;
    }

    /**
     * 查询声音统计信息
     *
     * @param trackId
     * @return
     */
    @Override
    public TrackStatVo getTrackStatVo(Long trackId) {
        return trackInfoMapper.getTrackStatVo(trackId);
    }

    @Autowired
    private AlbumStatMapper albumStatMapper;

    /**
     * 更新DB中声音/专辑统计数值
     *
     * @param mqVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrackStat(TrackStatMqVo mqVo) {
        //1.更新声音统计数值
        trackStatMapper.update(
                null,
                new LambdaUpdateWrapper<TrackStat>()
                        .eq(TrackStat::getTrackId, mqVo.getTrackId())
                        .eq(TrackStat::getStatType, mqVo.getStatType())
                        .setSql("stat_num = stat_num + " + mqVo.getCount())
        );

        //2.如果是"播放"or"评论"还需要更新专辑统计数值
        if (TRACK_STAT_PLAY.equals(mqVo.getStatType())) {
            //更新专辑统计表播放量
            albumStatMapper.update(
                    null,
                    new LambdaUpdateWrapper<AlbumStat>()
                            .eq(AlbumStat::getAlbumId, mqVo.getAlbumId())
                            .eq(AlbumStat::getStatType, ALBUM_STAT_PLAY)
                            .setSql("stat_num = stat_num + " + mqVo.getCount())
            );
        }
        if (TRACK_STAT_COMMENT.equals(mqVo.getStatType())) {
            //更新专辑统计表评论量
            albumStatMapper.update(
                    null,
                    new LambdaUpdateWrapper<AlbumStat>()
                            .eq(AlbumStat::getAlbumId, mqVo.getAlbumId())
                            .eq(AlbumStat::getStatType, ALBUM_STAT_COMMENT)
                            .setSql("stat_num = stat_num + " + mqVo.getCount())
            );
        }
    }

    /**
     * 基于当前用户未购买声音数量动态渲染分集购买列表
     *
     * @param userId  用户ID
     * @param trackId 选择购买声音ID，作为起始标准计算未购买声音数量
     * @return [{name:"本集",price:0.1,trackCount:1},{name:"后10集",price:1,trackCount:10}..,{name:"全集",price:3.8,trackCount:38}]
     */
    @Override
    public List<Map<String, Object>> findUserTrackPaidList(Long userId, Long trackId) {
        //1.根据选择购买声音ID查询声音记录，得到声音序号，得到专辑ID
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        Integer orderNum = trackInfo.getOrderNum();
        Long albumId = trackInfo.getAlbumId();
        //2.根据"起始声音"需要+专辑ID查询声音表得到“未购买声音列表”，这里可能包含已购买声音
        List<TrackInfo> waitBuyTrackList = trackInfoMapper.selectList(
                new LambdaQueryWrapper<TrackInfo>()
                        .eq(TrackInfo::getAlbumId, albumId)
                        .ge(TrackInfo::getOrderNum, orderNum)
                        .select(TrackInfo::getId)
        );

        //3.远程调用用户服务，得到用户已购声音ID列表，如果有值将已购买声音ID排除掉
        List<Long> userPaidTrackIdList = userFeignClient.findUserPaidTrackList(albumId).getData();
        if (CollUtil.isNotEmpty(userPaidTrackIdList)) {
            waitBuyTrackList =
                    waitBuyTrackList.stream()
                            .filter(t -> !userPaidTrackIdList.contains(t.getId()))
                            .collect(Collectors.toList());
        }

        //4.基于未购买声音数量，动态封装分集购买列表
        int size = waitBuyTrackList.size();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //4.0 查询专辑记录得到单集价格
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        BigDecimal price = albumInfo.getPrice();
        ///4.1 创建"本集"分集购买对象
        Map<String, Object> currMap = new HashMap<>();
        currMap.put("name", "本集");
        currMap.put("price", price);
        currMap.put("trackCount", 1);
        list.add(currMap);
        //4.2 创建"后i*10集"分集购买对象
        for (int i = 10; i < 50; i += 10) {
            Map<String, Object> map = new HashMap<>();
            if (i < size) {
                map.put("name", "后" + i + "集");
                map.put("price", price.multiply(new BigDecimal(i)));
                map.put("trackCount", i);
                list.add(map);
            } else {
                map.put("name", "全集(后" + size + "集)");
                map.put("price", price.multiply(new BigDecimal(size)));
                map.put("trackCount", size);
                list.add(map);
                break;
            }
        }
        return list;
    }

    /**
     * 查询用户未购买声音列表
     *
     * @param trackId    选择购买声音ID，作为起始标准计算未购买声音数量
     * @param trackCount 限制查询未购买声音数量
     * @return
     */
    @Override
    public List<TrackInfo> findWaitBuyTrackInfoList(Long userId, Long trackId, Integer trackCount) {
        //1.根据声音ID查询到“起始”待购声音记录-得到专辑ID及序号
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        Long albumId = trackInfo.getAlbumId();
        Integer orderNum = trackInfo.getOrderNum();

        //2.远程调用用户服务获取已购买声音ID列表
        List<Long> userPaidTrackList = userFeignClient.findUserPaidTrackList(albumId).getData();

        //3.构建查询条件查询未购买声音列表
        LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<TrackInfo>()
                .eq(TrackInfo::getAlbumId, albumId)
                .ge(TrackInfo::getOrderNum, orderNum)
                .orderByAsc(TrackInfo::getOrderNum)
                .select(TrackInfo::getId, TrackInfo::getTrackTitle, TrackInfo::getCoverUrl, TrackInfo::getAlbumId)
                .last("limit " + trackCount);
        if (CollUtil.isNotEmpty(userPaidTrackList)) {
            queryWrapper.notIn(TrackInfo::getId, userPaidTrackList);
        }
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(queryWrapper);
        return trackInfoList;
    }


    public static void main(String[] args) {
        //Integer内部IntegerCache缓存-127~127之间，IntegerCache缓存的Integer对象是同一个对象，
        Integer a = 1;
        Integer b = 1;
        System.out.println(a == b);


        Integer c = 128;
        Integer d = 128;
        System.out.println(c == d);
    }

}
